package com.orange.base.component.biztool.simulateddata.service.impl;

import java.util.List;
import java.util.Map;

import com.orange.base.component.biztool.simulateddata.service.SimulatedDataEnum;
import com.orange.base.component.biztool.simulateddata.service.SimulatedDataParam;

/**
 * 随机取固定表固定字段值
 *
 * @author biankudingcha
 * @date: 2022-08-24
 * @since 0.5.0
 */
public class TableColumnValueStrategy extends AbstractSimulatedData {

    private static final ThreadLocal<List<Map<String, Object>>> CONTEXT = new ThreadLocal<List<Map<String, Object>>>();

    public TableColumnValueStrategy() {

    }

    @Override
    public Object getValue(SimulatedDataParam param) {
        Object value = param.getValue();
        if (isEmpty(value)) {
            return null;
        }
        String[] values = toStr(value).split("\\.");
        if (values.length != 2) {
            return null;
        }
        List<Map<String, Object>> datas = null;
        if (CONTEXT.get() == null) {
            String sql = "SELECT " + values[1] + " FROM " + values[0];
            datas = simulatedDataDao.query(sql, 1, 10000, param.getExtParam());
            if (datas == null || datas.isEmpty()) {
                return null;
            }
            CONTEXT.set(datas);
        } else {
            datas = CONTEXT.get();
        }
        int index = getRandomNumber(0, datas.size() - 1);
        return datas.get(index - 1).get(values[1]);
    }

    @Override
    public String getType() {
        return SimulatedDataEnum.TABLE_COLUMN_VALUE.getName();
    }

    @Override
    public String getCaption() {
        return SimulatedDataEnum.TABLE_COLUMN_VALUE.getCaption();
    }

    public String getDescriptions() {
        return "格式:表名称.列名称";
    }

}
